/**
 *  *2010-5-24 下午12:09:05  add 
 */
package com.base.myproject.client.busi.service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.print.PrintDialogX;
import com.base.myproject.client.busi.print.Printer;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncGetModelDatas;
import com.base.myproject.client.tools.CommandSyncHasCcodeNotPass;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.Loading;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseRadioGroup;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * 2010-11-14 加入次卡，次卡要和消费配合。次卡的编号是C开始
 * @author Administrator 2010-5-24 javazgw@gmail.com
 */
public class AddFinace_acc implements Printer{
	CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
	// 会员充值账户信息
	List<Finace_accitem> fas = new LinkedList<Finace_accitem>();
	String ccode;// 会员
	String bcode;// 充值人员
	

	TextField<String> s_cardno;
	BaseComboBoxForm<BaseModelData>  rbcode_t=null; //充值推销人员
	//rbcode_t = createBcode_filter()
	NumberField finace;
	Dialog d = new Dialog();
	 String[] strarr = new String[]{"储值卡","消费次卡"};
	 BaseRadioGroup brg = new BaseRadioGroup(strarr);
	
	 Html html = new Html();
	int isnew =1;//0：新的会员充值，1 老会员充值，默认老会员
	
	int addfinanceProperty =1;
	final int CAN_ADD_TO_OTHER_ACC = 1;//可以给指定行充值，充值的时候光标所在的行，默认可以
	public AddFinace_acc() {
		
		d.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.addfinance()));
		brg.setValue(1);
		html.setWidth("150px");
		html.setHeight("100px");
	}
	
	public int getAddFinaceProperty() {
		return addfinanceProperty;
	}

	public void setAddFinaceProperty(int addfinanceProperty) {
		this.addfinanceProperty = addfinanceProperty;
	}
	
	public void addAddFinaceProperty(int paidaddfinancePropertyProperty) {
		this.addfinanceProperty = this.addfinanceProperty | addfinanceProperty;
	}

	public void showDialog() {
		rbcode_t = createBcode_filter();
		//rbcode_t.setAllowBlank(false);
		FormPanel formpanel = new FormPanel();
		formpanel.setHeaderVisible(false);
		d.setWidth("100");

		d.setHeading("会员充值");
		s_cardno = new TextField<String>();
		s_cardno.setFieldLabel("会员卡号");
		s_cardno.addListener(Events.Change, getListener());

		brg.setFieldLabel("卡类型");
		
		finace = new NumberField();
		finace.setFieldLabel("充值金额/次数");
		//finace.addListener(Events.Change, getListener());
		finace.addListener(Events.KeyUp, getListener());
		rbcode_t.setFieldLabel("销售人员");
		formpanel.add(s_cardno);
		
		formpanel.add(brg);
		formpanel.add(finace);
		formpanel.add(rbcode_t);
		
		formpanel.add(createFinaceGrid());
		formpanel.add(html);
		
		d.setSize(550, 450);
		d.add(formpanel);
		d.setButtons(Dialog.OKCANCEL);

		d.getButtonById(Dialog.CANCEL)
				.addListener(Events.Select, getListener());
		d.getButtonById(Dialog.OK).addListener(Events.Select, getListener());
//		finace.addListener(Events.Change, getListener());
		brg.addListener(Events.Change, getListener());
		d.show();
	}

	BaseStore<BusiObject> finacestore = new BaseStore<BusiObject>();
	BaseGrid<BusiObject> fg;

	BaseGrid<BusiObject> createFinaceGrid() {
		
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

//		ColumnConfig C1 = new ColumnConfig("code", "code", 80);
//		columns.add(C1);
		ColumnConfig C2 = new ColumnConfig("name", "账户名称", 120);
		columns.add(C2);
		ColumnConfig C7 = new ColumnConfig("amount", "<金额/次", 80);
		columns.add(C7);
		ColumnConfig C3 = new ColumnConfig("lastamount", "账户余额/次", 80);
		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("finance", "充值金额/次", 80);
		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("s_discount", "服务折扣", 80);
		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("g_discount", "商品折扣", 80);
		columns.add(C6);
		ColumnModel cm = new ColumnModel(columns);
		 fg = new BaseGrid<BusiObject>(finacestore, cm, false, false);
		 cbs.setSelectionMode(SelectionMode.SINGLE);
		 fg.setSelectionModel(cbs);
		fg.setHeight(200);
		fg.getView().setForceFit(true);
		//是否可写，不可写就不能选择，能选择就可以个其他账户充值
		if((getAddFinaceProperty() & CAN_ADD_TO_OTHER_ACC)!=CAN_ADD_TO_OTHER_ACC)
		{
		fg.setEnabled(false);
		}
		cbs.addListener(Events.SelectionChange, getListener());
		return fg;
	}

	public String getCcode() {
		return ccode;
	}

	public void setCcode(String ccode) {
		this.ccode = ccode;
	}

	public String getBcode() {
		return bcode;
	}

	public void setBcode(String bcode) {
		this.bcode = bcode;
	}

	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							 if (be.getSource().equals(d.getButtonById(Dialog.CANCEL))) {
								 d.setVisible(false);
							 }
							 else if (be.getSource().equals(d.getButtonById(Dialog.OK))) {
								
								 if(fg.getSelectionModel().getSelectedItems().size()==0)
								 {
									MessageBox.alert("错误", "请先选择充值的账户", null);
									return;
								 }
								  d.getButtonById(Dialog.OK).setEnabled(false);
								 
								 
								 CommandSyncContainer list = new CommandSyncContainer();
								 
								 CommandSyncHasCcodeNotPass cshcnp = new CommandSyncHasCcodeNotPass();
									cshcnp.setS_cardno(s_cardno.getValue());
									cshcnp.setContinueorrollback(false);
									
								 CommandSyncsql csql = new CommandSyncsql();
								 
								 csql.setContinueorrollback(false);
								 
								 
								String code = fg.getSelectionModel().getSelectedItem().get("code");
							//	 csql.getV().add("insert into s_service_finance (ccode,finance,accountcode) values ('"+"186"+"',"+finace.getValue().doubleValue()+",'"+code+"')");,'"+Env.getEnvbcode()+"','"+rbcode_t.getValue()+"
								 csql.getV().add("insert into s_service_finance (ccode,finance,accountcode,updatedate,bcode,rbcode,isnew) select ccode,"+finace.getValue().doubleValue()+",'"+code+"',getdate(),'"+Env.getEnvbcode()+"','"+rbcode_t.getValueCode()+"',"+isnew+" from ccode where s_cardno='"+s_cardno.getValue()+"'");
								 GWT.log("insert into s_service_finance (ccode,finance,accountcode,updatedate,bcode,rbcode,isnew) select ccode,"+finace.getValue().doubleValue()+",'"+code+"',getdate(),'"+Env.getEnvbcode()+"','"+rbcode_t.getValueCode()+"',"+isnew+" from ccode where s_cardno='"+s_cardno.getValue()+"'");
								 list.add(cshcnp);
								 list.add(csql);
								 
								 GreetingServiceAsync greetingService = GWT
									.create(GreetingService.class);
								 greetingService
									.SendCommandSync(
											list,
											new AsyncCallback<CommandSyncReturnObject>() {
												@Override
												public void onFailure(
														Throwable caught) {
													MessageBox.alert("错误",
															"网络连接失败", null);
													d.getButtonById(Dialog.OK).setEnabled(true);
												}
												@Override
												public void onSuccess(
														CommandSyncReturnObject result) {
													if (result.isB()) {
														Info.display("", "充值成功");
														Print();
													}
													else{
														MessageBox.alert("错误",
																"错误，错误代码"+result.getMessage(), null);
														d.getButtonById(Dialog.OK).setEnabled(true);
													}
												}
											});
								 
							 }
							// else if(be.getSource().equals(savesalary))
							// {}
							// else if(be.getSource().equals(save))
							// {}
							// else if(be.getSource().equals(prequery))
							// {}

						} else if (be.getType() == Events.Change) {

							if (be.getSource().equals(s_cardno)) {
								Loading.getinstance().connecting("获取会员资料");
								
								
								final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
								.create(com.base.myproject.client.tools.GreetingService.class);
								
								
								greetingService.getAssociator(s_cardno.getValue(),4,new AsyncCallback<Associator>(){

									@Override
									public void onFailure(Throwable caught) {
										
										MessageBox.alert("错误",
												"网络连接失败", null);
									}

									@Override
									public void onSuccess(Associator result) {
										
										showmessage(result);
									}});
								
								
								CommandSyncContainer list = new CommandSyncContainer();

								
								CommandSyncHasCcodeNotPass cshcnp = new CommandSyncHasCcodeNotPass();
								cshcnp.setS_cardno(s_cardno.getValue());
								cshcnp.setContinueorrollback(false);
								
								
								CommandSyncGetModelDatas csgmd = new CommandSyncGetModelDatas();
								csgmd.setSqlname("s_finace_add");
								csgmd.putmacro("SCARDNO", s_cardno.getValue());
								list.add(cshcnp);
								list.add(csgmd);
//								final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
//										.create(com.base.myproject.client.tools.GreetingService.class);
								greetingService
										.SendCommandSync(
												list,
												new AsyncCallback<CommandSyncReturnObject>() {

													@Override
													public void onFailure(
															Throwable caught) {
														MessageBox.alert("错误",
																"网络连接失败", null);
														Loading.getinstance().connected();
													}

													@Override
													public void onSuccess(
															CommandSyncReturnObject result) {
														Loading.getinstance().connected();
														if (result.isB()) {
															// BaseStore<BusiObject>
															// salarystore = new
															// BaseStore<BusiObject>();
															if (result
																	.getCommandsync() instanceof CommandSyncGetModelDatas) {
																// salarystore.add(((CommandSyncGetModelDatas)(result.getCommandsync())).getList(),false);
																// System.out.println(salarystore.getCount());
																System.out.println(((CommandSyncGetModelDatas)(result.getCommandsync())).getList());
															
																finacestore.removeAll();
																finacestore.add(((CommandSyncGetModelDatas)(result.getCommandsync())).getList(),false);
																
																finacestoreFilter();
																
															}

														} else {
															MessageBox
																	.alert(
																			"错误",
																			"错误未知！"
																					+ result
																							.getMessage(),
																			null);

														}

													}

												});
							}
							
						
							else if(be.getSource().equals(brg))
							{
								finacestoreFilter();
							}
						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}
							}
							if (be.getSource().equals(finace))
							{
								inputfinace();
							}
							
							
						}
						else if(be.getType() == Events.SelectionChange)
						{
							//如果选中行，则强制按照选中的账户进行充值。
							if(be.getSource().equals(cbs))
							{
								if(finacestore!=null && finacestore.getCount()>0)
								{
								for(int i = 0 ;i<finacestore.getCount();i++)
								{
									finacestore.setValue(i, "finance", null);
								}
//								fg.getSelectionModel().getSelectedItem()
								double d = 0;
								if(finace.getValue()!=null)
									{ d = finace.getValue().doubleValue();}
								finacestore.setValue( "finance", d);
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}
	
	void finacestoreFilter()
	{
		if(finacestore!=null)
		{
			GWT.log("brg value = "+brg.getValue());
			if(brg.getValue().intValue()==1)
			{
				finacestore.filter("code", "A");
				inputfinace();
			}
			else if(brg.getValue().intValue()==2)
			{
				finacestore.filter("code", "C");
				inputfinace();
			}
			else
			{
			finacestore.clearFilters();
			}
		}
	}
	/*
	 * 
	 * 录入充值金额
	 */
	
	void inputfinace()
	{
		


		clearselect();
		double d = 0;
		if(finace.getValue()!=null)
		{ d = finace.getValue().doubleValue();}
		
		for(int i = 0 ;i<finacestore.getCount();i++)
		{
			
			if (i == 0) {
				double amount1 = Double
				.parseDouble(finacestore
						.getValue(i, "amount")
						.toString());
				if(d<=amount1)
				{
					finacestore.setValue(i, "finance", d);
					fg.getSelectionModel().select(finacestore.getAt(i), true);
					break;
				}
			}

			 if (i == finacestore.getCount() - 1) {
				
				finacestore.setValue(i, "finance", d);
				fg.getSelectionModel().select(finacestore.getAt(i), true);
				break;

			} 
			 
			 {
				double amount1 = Double
						.parseDouble(finacestore
								.getValue(i, "amount")
								.toString());
				double amount2 = Double
						.parseDouble(finacestore
								.getValue(i+1, "amount")
								.toString());

				System.out.println("amount1="+amount1);
				System.out.println("amount2="+amount2);
				if (d >= amount1 && d < amount2) {
					
					finacestore.setValue(i, "finance", d);
					fg.getSelectionModel().select(finacestore.getAt(i), true);
					break;

				}
			}
		}
		
	
	
	}
	
	void showmessage(Associator result)
	{
	//	
		html.el().makePositionable(true);
		html.el().setTop(12);
		html.el().setLeft(333);
		
//		Dialog messagedialog = new Dialog();
		String str = "<ul style='font-size:12px'><li>会员卡号："+(result.getS_cardno()==null?"":result.getS_cardno())+"</li>";
		str +="<li>名称："+(result.getName()==null?"":result.getName())+"</li>";
		str +="<li>电话："+(result.getPhone()==null?"":result.getPhone())+"</li></ul>";
		
		html.setHtml(str);
//		messagedialog.add(html);
//		messagedialog.setButtons(Dialog.OKCANCEL);
//		messagedialog.getbu
	}
	/**
	 * 取消设置
	 */
	void clearselect(){
		
		fg.getSelectionModel().deselectAll();
		for(int i = 0 ;i<finacestore.getCount();i++)
		{
			finacestore.setValue(i, "finance", null);
		}
	}

	@Override
	public void Print() {
		//String icode =store.getValue("icode").toString();
		PrintDialogX printdialog = new PrintDialogX("6002","&s_cardno="+s_cardno.getValue());
		printdialog.show();
		
	}
	
	
	public int getIsnew() {
		return isnew;
	}
/**
 * 0：新的会员充值，1 老会员充值，默认老会员
 * @param isnew
 */
	public void setIsnew(int isnew) {
		this.isnew = isnew;
	}
//销售人员，只显示本公司人员
	BaseComboBoxForm<BaseModelData> createBcode_filter()
	{
		
		BaseStore<BaseModelData> base_filter;
			ModelType type = new ModelType();
			type.setRoot("records");
			type.setRecordName("record");
			type.setTotalName("totle");
			type.addField("code");
			type.addField("name");
			StoreInfo info = new StoreInfo();
			info.setTablename("bcode");
			info.setNeedAllRow("no");
			info.setForcenolimit("true");
			info.setSql("select bcode as code,bname as name from bcode where bcode is not null and bname is not null and systemid in (select systemid from bcode where bcode= '"+Env.getEnvbcode()+"')");
			base_filter = new BaseStore<BaseModelData>(type,info);
	
		BaseComboBoxForm<BaseModelData> bcbf = new BaseComboBoxForm<BaseModelData>(base_filter);
		return bcbf;
	}
}
